package cn.iocoder.yudao.module.ai.graph.node.customerservice;

import com.alibaba.cloud.ai.graph.GraphResponse;
import com.alibaba.cloud.ai.graph.OverAllState;
import com.alibaba.cloud.ai.graph.action.NodeAction;
import com.alibaba.cloud.ai.graph.streaming.FluxConverter;
import com.alibaba.cloud.ai.graph.streaming.StreamingOutput;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatResponse;
import reactor.core.publisher.Flux;

import java.util.Map;

/**
 * 问题分类节点 - 自动分析客户问题的类型、优先级和情绪
 * 
 * @author yudao
 * @since 2025/10/17
 */
public class ClassifyQueryNode implements NodeAction {

    private static final Logger logger = LoggerFactory.getLogger(ClassifyQueryNode.class);

    private static final String CLASSIFY_PROMPT_TEMPLATE = """
        你是一个专业的客服问题分类助手。请分析以下客户问题，并返回 JSON 格式的分类结果。
        
        客户问题：%s
        
        客户上下文：%s
        
        请分析并返回以下信息（必须严格返回 JSON 格式）：
        {
          "category": "问题类别（产品咨询/技术支持/售后服务/投诉建议/账户问题）",
          "priority": "优先级（high/medium/low）",
          "sentiment": "情绪（positive/neutral/negative）",
          "keywords": ["关键词1", "关键词2"],
          "requires_human": "是否需要人工介入（true/false）"
        }
        
        只返回 JSON，不要有其他文字。
        """;

    private final ChatClient chatClient;

    public ClassifyQueryNode(ChatClient.Builder chatClientBuilder) {
        this.chatClient = chatClientBuilder.build();
    }

    @Override
    public Map<String, Object> apply(OverAllState state) {
        logger.info("=== ClassifyQueryNode 开始执行 ===");
        
        String query = state.value("customer_query", "");
        String context = state.value("customer_context", "");
        
        logger.info("客户问题：{}", query);

        // 格式化提示词
        String prompt = String.format(CLASSIFY_PROMPT_TEMPLATE, query, context);
        
        // 调用 AI 模型进行分类
        Flux<ChatResponse> chatResponseFlux = this.chatClient.prompt()
                .user(prompt)
                .stream()
                .chatResponse();

        // 转换为流式输出
        Flux<GraphResponse<StreamingOutput>> generator = FluxConverter.builder()
                .startingNode("classify_stream")
                .startingState(state)
                .mapResult(response -> {
                    String text = response.getResult().getOutput().getText();
                    logger.info("分类结果：{}", text);
                    
                    try {
                        // 解析 JSON 结果
                        JSONObject result = JSON.parseObject(text);
                        return Map.of(
                            "query_category", result.getString("category"),
                            "query_priority", result.getString("priority"),
                            "query_sentiment", result.getString("sentiment")
                        );
                    } catch (Exception e) {
                        logger.error("解析分类结果失败", e);
                        return Map.of(
                            "query_category", "技术支持",
                            "query_priority", "medium",
                            "query_sentiment", "neutral"
                        );
                    }
                })
                .build(chatResponseFlux);

        return Map.of("classify_result", generator);
    }
}

